package cn.wang.page.service;

import cn.wang.page.Client.BrandClient;
import cn.wang.page.Client.CategoryClient;
import cn.wang.page.Client.GoodsClient;
import cn.wang.page.Client.SpecClient;
import cn.wang.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.File;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class PageService {

    @Autowired
    GoodsClient goodsClient;
    @Autowired
    SpecClient specClient;
    @Autowired
    CategoryClient categoryClient;
    @Autowired
    BrandClient brandClient;
    @Autowired
    TemplateEngine templateEngine; // thymeleaf 模板解析器


    public Map<String, Object> queryPage(Long spuId) {
        Map<String,Object> map = new HashMap<>();
        Spu spu = goodsClient.queryGoodBySpuId(spuId);
        SpuDetail spuDetail = spu.getSpuDetail();
        List<Sku> skus = spu.getSkus();
        Brand brand = brandClient.queryBrandByBId(spu.getBrandId());
        List<Category> categoryList = categoryClient.queryCategorysByCids(spu.getCid1(), spu.getCid2(), spu.getCid3());
        List<SpecGroup> specs = specClient.queryGroupsAllByCid(spu.getCid3());
        map.put("spu",spu);
        map.put("detail",spuDetail);
        map.put("skus",skus);
        map.put("brand",brand);
        map.put("categories",categoryList);
        map.put("specs",specs);
        return map;

    }

    /**
     * 根据spuId创建静态页面
     * @param spuId
     */
    public void createTemplate(Long spuId){
        Context context = new Context();
        context.setVariables(queryPage(spuId));
        File file = new File("G:\\item", spuId + ".html");
        // 如果文件存在先删除
        if (file.exists()) {
            file.delete();
        }
        try(PrintWriter writer = new PrintWriter(file, "UTF-8")){
            // 对页面进行静态化, 将静态化的结果直接交给nginx, 让nginx进行转发,提高并发量
            // 当商品的数据发生改变后,对静态页面进行更新,
            // 使用rabbitmq消息队列的方式实现
            templateEngine.process("item", context,writer); // 提供模板地址和数据,以及输出流(结果生成的地方)
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 根据spuid删除静态页面
     * @param spuId
     */
    public void DeleteTemplate(Long spuId) {
        File file = new File("G:\\item", spuId + ".html");
        if (file.exists()) {
            file.delete();
        }
    }
}
